const TelegramBot = require('node-telegram-bot-api');
const User = require('./models/User');
const GigaChat = require('gigachat-node').GigaChat;

const bot = new TelegramBot(process.env.BOT_TOKEN, { 
    polling: true
});

const client = new GigaChat(
    clientSecretKey=process.env.GIGACHAT_TOKEN,
    isIgnoreTSL=true,
    isPersonal=true,
    true,
    true,
    './image'
);
client.createToken();

const startBot = () => {
    bot.on('message', async (msg) => {
        try {
            const chatId = msg.chat.id;
            const user = await User.findOne({ chatId });
            if(msg.text === '/start') {
                if(!user) {
                    User.create({ chatId });
                }
    
                await bot.sendMessage(chatId, 'Добро пожаловать в GigaChat-Бот!');
            }
            else {
                const waitMessage = await bot.sendMessage(chatId, 'Пожалуйста, подождите...');
                await bot.sendChatAction(chatId, 'typing');

                try {
                    const messages = [
                        {
                            role: "user",
                            content: user.lastMessage,
                        },
                        {
                            role: "assistant",
                            content: user.lastCompetion
                        },
                        {
                            role: "user",
                            content: msg.text
                        }
                    ]

                    const responce = await client.completion({
                        "model": "GigaChat:latest",
                        "messages": messages
                    });
                    let completion = responce.choices[0].message.content;
    
                    if(responce.choices[0].message.image) {
                        completion = "Может нарисовать что-то еще? Я могу нарисовать что угодно."
                        bot.sendPhoto(chatId, responce.choices[0].message.image, {
                            caption: completion
                        });
                    }
                    else {
                        bot.sendMessage(chatId, completion, {
                            parse_mode: 'Markdown'
                        });
                    }

                    user.lastMessage = msg.text;
                    user.lastCompetion = completion;
                    user.save();
                    bot.deleteMessage(chatId, waitMessage.message_id);
                }
                catch(error) {
                    await bot.sendMessage(chatId, 'Не удалось сгенерировать ответ!');
                    bot.deleteMessage(chatId, waitMessage.message_id);
                }
            }
        }
        catch(error) {
            console.log(error);
        }
    })
}

module.exports = {
    startBot: startBot
}